<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="拜访目标" prop="visitObjectivesName">
        <el-input
          v-model="queryParams.visitObjectivesName"
          placeholder="请输入拜访目标"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="进度" prop="visitObjectivesSchedule">
        <el-input
          v-model="queryParams.visitObjectivesSchedule"
          placeholder="请输入进度"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="公司名称" prop="visitObjectivesCompanyName">
        <el-input
          v-model="queryParams.visitObjectivesCompanyName"
          placeholder="请输入公司名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      
      <el-form-item label="负责人" prop="visitObjectivesPrincipalName">
        <el-input
          v-model="queryParams.visitObjectivesPrincipalName"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:objectives:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:objectives:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:objectives:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['crm:objectives:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="objectivesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" width="55" align="center" prop="visitObjectivesId" />
      <el-table-column label="拜访目标" align="center" prop="visitObjectivesName" />
      <!--
      <el-table-column label="进度" align="center" prop="visitObjectivesSchedule" :formatter="showScheduleLabel"/>
      -->
      <el-table-column label="进度" align="center" prop="visitObjectivesSchedule">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.crm_objectives_schedule" :value="scope.row.visitObjectivesSchedule"/>
          </template>
      </el-table-column>
      
      <el-table-column label="公司名称" align="center" prop="visitObjectivesCompanyName" />
      <el-table-column label="负责人" align="center" prop="visitObjectivesPrincipalName" />
      <el-table-column label="录入人" align="center" prop="visitObjectivesUserName" />
      <el-table-column label="录入时间" align="center" prop="visitObjectivesDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitObjectivesDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column width="240" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <router-link  :to="'/crm/visit-record/index/' + scope.row.visitObjectivesId" class="link-type">
              <el-button style="width:80px"
              size="mini"
              type="text"
              icon="el-icon-share"
              v-hasPermi="['crm:objectives:edit']"
            >拜访记录 </el-button>
          </router-link> 
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:objectives:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:objectives:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拜访目标对话框 -->
    <el-dialog  :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="visitObjectivesCompanyId">
          <el-select v-model="form.visitObjectivesCompanyId" ref="companySelect" placeholder="请选择" style="width:100%">
            <el-option
              v-for="company in companies"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
           <treeselect v-model="deptId"  :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="form.visitObjectivesPrincipalId" ref="userSelect" placeholder="请选择" style="width:100%">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拜访目标" prop="visitObjectivesName">
          <el-input v-model="form.visitObjectivesName" placeholder="请输入拜访目标" />
        </el-form-item>
        
        <el-form-item label="进度">
              <el-select v-model="form.visitObjectivesSchedule" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="dict in dict.type.crm_objectives_schedule"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>

        <el-form-item  prop="visitObjectivesCompanyName" v-show="false">
          <el-input v-model="form.visitObjectivesCompanyName"/>
        </el-form-item>
        
        <el-form-item label="描述" prop="visitObjectivesDesc">
          <el-input v-model="form.visitObjectivesDesc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="负责人" prop="visitObjectivesPrincipalName" v-show="false">
          <el-input v-model="form.visitObjectivesPrincipalName" placeholder="请输入负责人" />
        </el-form-item>
        
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listObjectives, getObjectives, delObjectives, addObjectives, updateObjectives, exportObjectives } from "@/api/crm/objectives";

import { getusers,selectUserById } from "@/api/system/user";
import { getCompanies } from "@/api/crm/linkman";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

export default {
  name: "Objectives",
  dicts: ['crm_objectives_schedule'],
  components: { Treeselect },
  data() {
    return {
      // 所属公司选项
      companies: [],
      deptId: undefined,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拜访目标表格数据
      objectivesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树数据
      deptOptions: [],
      //負責人
      users: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        visitObjectivesName: null,
        visitObjectivesSchedule: null,
        visitObjectivesCompanyId: null,
        visitObjectivesCompanyName: null,
        visitObjectivesDesc: null,
        visitObjectivesPrincipalId: null,
        visitObjectivesPrincipalName: null,
        visitObjectivesUserId: null,
        visitObjectivesUserName: null,
        visitObjectivesDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询拜访目标列表 */
    getList() {
      this.loading = true;
      listObjectives(this.queryParams).then(response => {
        this.objectivesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        visitObjectivesId: null,
        visitObjectivesName: null,
        visitObjectivesSchedule: null,
        visitObjectivesCompanyId: null,
        visitObjectivesCompanyName: null,
        visitObjectivesDesc: null,
        visitObjectivesPrincipalId: null,
        visitObjectivesPrincipalName: null,
        visitObjectivesUserId: null,
        visitObjectivesUserName: null,
        visitObjectivesDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.visitObjectivesId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      getCompanies().then(response => {
        this.companies = response.companies;
      });
      this.open = true;
      this.title = "添加拜访目标";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const visitObjectivesId = row.visitObjectivesId || this.ids
      getObjectives(visitObjectivesId).then(response => {
        this.form = response.data;
        //填充公司并选中
        getCompanies().then(response => {
          this.companies = response.companies;
          this.$refs.companySelect.selected.value = this.form.visitObjectivesCompanyId;
        });
        //填充树并选中
        this.getTreeselect();
        //根据负责人id获得所在部门
        selectUserById(this.form.visitObjectivesPrincipalId).then(response => {
          let u = response.user;
          this.deptId = u.deptId;
          
          getusers({"deptId": u.deptId}).then(response => {
            this.users = response.users;
            this.form.visitObjectivesPrincipalId = u.userId;
            this.form.visitObjectivesPrincipalName = u.nickName;
            this.$refs.userSelect.selected.value = this.form.visitObjectivesPrincipalId;
            
         });
        });
        this.open = true;
        this.title = "修改拜访目标";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //取得select的label值
          this.form.visitObjectivesCompanyName = this.$refs.companySelect.selected.label;
          this.form.visitObjectivesPrincipalName = this.$refs.userSelect.selected.label;
          if (this.form.visitObjectivesId != null) {
            updateObjectives(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addObjectives(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const visitObjectivesIds = row.visitObjectivesId || this.ids;
      this.$modal.confirm('是否确认删除拜访目标编号为"' + visitObjectivesIds + '"的数据项？').then(function() {
        return delObjectives(visitObjectivesIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    
    onDeptChange(v){
      this.users = [];
      this.form.visitObjectivesPrincipalName = '';
      this.form.visitObjectivesPrincipalId = '';
      //undefined是一种类型，不是一个值
      if (v !== undefined) {
         getusers({"deptId": v}).then(response => {
           this.users = response.users;
         });
      }
    },

    //改变表格中进度数据，将数字转为具体文字
    showScheduleLabel(row, column){

      switch(row.visitObjectivesSchedule) {
        case '0': {
            return '未开始';
        }
        case '1': {
            return '进行中';
        }
        default: {
            return '已完成';
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有拜访目标数据项？').then(() => {
        this.exportLoading = true;
        return exportObjectives(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  },
  watch: {
    'deptId' : 'onDeptChange'
  }
};
</script>
